package com.websocket.hander;

import com.websocket.service.WebSocketConnection;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Method;
import java.security.Principal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HandlerExecutionChain {

    private final List<HandlerInterceptor> interceptors = new ArrayList<>();

    public HandlerExecutionChain() {
    }

    public HandlerExecutionChain(List<HandlerInterceptor> interceptors) {
        this.interceptors.addAll(interceptors);
    }

    public HandlerExecutionChain addInterceptor(HandlerInterceptor interceptor) {
        interceptors.add(interceptor);
        return this;
    }

    public boolean applyHandle(WebSocketConnection conn, Map<String, Object> params, Method handler, Principal user) {
        if (CollectionUtils.isEmpty(interceptors)) return true;
        for (HandlerInterceptor interceptor : interceptors) {
            if (!interceptor.preHandle(handler, params, conn, user)) {
                return false;
            }
        }
        return true;
    }
}
